<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import Breadcrumb from '../components/Breadcrumb.vue'
import Bell from '../components/Bell.vue'
import { Bell as BellIcon } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const isCollapse = ref(false)
const activeMenu = computed(() => route.path)
const currentUser = computed(() => userStore.userInfo)
const isLoggedIn = computed(() => !!userStore.userInfo && !!userStore.userInfo.id && !!userStore.userInfo.role)

function handleMenuClick(path) {
  if (!isLoggedIn.value) {
    router.push('/login')
    return
  }
  router.push(path)
}

onMounted(async () => {
  try {
    // 如果已登录，获取最新的用户信息
    if (userStore.isLoggedIn) {
      await userStore.getUserInfo()
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 不自动跳转，让游客也能看到界面
  }
})

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logout()
    router.push('/login')
    ElMessage.success('已退出登录')
  }).catch(() => {})
}

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 根据用户角色显示不同的菜单
const showMenu = (roles) => {
  if (!roles || roles.length === 0) return true
  return roles.includes(userStore.userInfo.role)
}
</script>

<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '220px'" class="sidebar">
      <div class="logo">
        <span v-if="!isCollapse">员工管理系统</span>
        <el-icon v-else><Management /></el-icon>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
        <el-menu-item index="/home" @click="handleMenuClick('/home')">
          <el-icon><HomeFilled /></el-icon>
          <template #title>首页</template>
        </el-menu-item>
        
        <!-- 人事管理员和部门管理员可见 -->
        <el-menu-item 
          index="/department" 
          v-if="showMenu(['HR_ADMIN', 'DEPARTMENT_MANAGER'])"
          @click="handleMenuClick('/department')"
        >
          <el-icon><OfficeBuilding /></el-icon>
          <template #title>部门管理</template>
        </el-menu-item>
        
        <!-- 人事管理员可见 -->
        <el-menu-item 
          index="/position" 
          v-if="showMenu(['HR_ADMIN'])"
          @click="handleMenuClick('/position')"
        >
          <el-icon><Postcard /></el-icon>
          <template #title>岗位管理</template>
        </el-menu-item>
        
        <!-- 人事管理员可见 -->
        <el-menu-item 
          index="/employee" 
          v-if="showMenu(['HR_ADMIN'])"
          @click="handleMenuClick('/employee')"
        >
          <el-icon><User /></el-icon>
          <template #title>员工管理</template>
        </el-menu-item>
        
        <!-- 薪资管理：管理员和部门经理可见 -->
        <el-menu-item index="/salary" v-if="showMenu(['HR_ADMIN', 'DEPARTMENT_MANAGER'])" @click="handleMenuClick('/salary')">
          <el-icon><Money /></el-icon>
          <template #title>薪资管理</template>
        </el-menu-item>

        <!-- 薪资发放：普通员工可见 -->
        <el-menu-item index="/payroll" v-if="showMenu(['EMPLOYEE', 'USER', '普通员工'])" @click="handleMenuClick('/payroll')">
          <el-icon><Money /></el-icon>
          <template #title>薪资发放</template>
        </el-menu-item>

        <!-- 所有人可见 -->
        <el-menu-item index="/attendance" @click="handleMenuClick('/attendance')">
          <el-icon><Calendar /></el-icon>
          <template #title>考勤管理</template>
        </el-menu-item>
        
        <!-- 所有人可见 -->
        <el-menu-item index="/leave" @click="handleMenuClick('/leave')">
          <el-icon><DocumentRemove /></el-icon>
          <template #title>请假管理</template>
        </el-menu-item>
        
        <!-- 所有人可见 -->
        <el-menu-item index="/ai" @click="handleMenuClick('/ai')">
          <el-icon><ChatDotRound /></el-icon>
          <template #title>智能助手</template>
        </el-menu-item>

        <!-- 所有人可见 -->
        <el-menu-item index="/notifications" @click="handleMenuClick('/notifications')">
          <el-icon><BellIcon /></el-icon>
          <template #title>消息中心</template>
        </el-menu-item>

        <!-- 所有人可见 -->
        <el-menu-item index="/profile" @click="handleMenuClick('/profile')">
          <el-icon><UserFilled /></el-icon>
          <template #title>个人信息</template>
        </el-menu-item>

         <!-- 所有人可见 -->
        
      </el-menu>
    </el-aside>
    
    <el-container class="right-container">
      <!-- 顶部导航 -->
      <el-header class="header">
        <div class="header-left">
          <el-icon class="toggle-icon" @click="toggleCollapse">
            <Fold v-if="!isCollapse" />
            <Expand v-else />
          </el-icon>
          <Breadcrumb />
        </div>
        
        <div class="header-right" style="display: flex; align-items: center;">
          <Bell class="bell-large" />
          <!-- 游客显示登录按钮 -->
          <el-button 
            v-if="!isLoggedIn" 
            type="primary" 
            size="small" 
            @click="router.push('/login')"
            style="margin-left: 10px;"
          >
            登录
          </el-button>
          <!-- 已登录用户显示用户名和下拉菜单 -->
          <el-dropdown v-else trigger="click">
            <span class="user-info">
              <span>{{ currentUser.name }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="router.push('/profile')">
                  <el-icon><UserFilled /></el-icon>个人信息
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <!-- 内容区域 -->
      <el-main class="main">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
.layout-container {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

.sidebar {
  background-color: #304156;
  transition: width 0.3s;
  overflow-x: hidden;
  height: 100vh;
}

.right-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  overflow: hidden;
}

.header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
}

.toggle-icon {
  font-size: 20px;
  cursor: pointer;
  margin-right: 15px;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.main {
  background-color: #f0f2f5;
  padding: 0;
  flex: 1;
  overflow-y: auto;
  height: calc(100vh - 60px);
}

.bell-large {
  margin-right: 120px !important;
  font-size: 40px !important;
}
</style>